const http = require('http');
const request = require('request');
const querystring = require('querystring');
const server = http.createServer((req, res) => {
    res.setHeader("Access-Control-Allow-Origin", '*');
    res.setHeader("Access-Control-Allow-Methods", "*");
    res.setHeader("Access-Control-Allow-Headers", "Content-Type,request-origin"); // 设置请求头中允许携带的参数
    res.setHeader("Cache-Control", "no-store");
    res.setHeader("Content-type", "application/json"); // 设置接口的返回类型
    const methods = req.method;
    const url = req.url;
    const path = url.split('?')[0];
    if(methods === 'POST') {
        let postData = '';
        req.on('data', chunk => {
            postData += chunk.toString();
        })
        req.on('end', () => { //监听数据流
            console.log(JSON.stringify(postData), 'data', postData);
            request.post('http://localhost:8000/api/user/login', JSON.stringify(postData), (error, response, bod) => {
                res.end(bod)
            })
        })
    } else if(methods === 'GET') {
        let data = querystring.parse(url.split('?')[1]);
        request.get('http://localhost:8000'+url, (error, response, bod) => {
            console.log(url, bod);
            res.end(JSON.stringify(data));
        })
    } else {
        res.end();
    }  
}) 
server.listen(8080);
console.log(8080)